package com.pp.pingpong;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener {
	
	
	private TextView X;
	private TextView Y;
	private TextView Z;
	private TextView Direction;
	
	private boolean mInitialized;
	
	private float mLastX, mLastY, mLastZ;
	private float time;
	private Sensor sensor;
	
	int Vcounter, Hcounter;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);		
		
		mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
		
		
		X = (TextView) findViewById(R.id.X);
		Y = (TextView) findViewById(R.id.Y);
		Z = (TextView) findViewById(R.id.Z);
		Direction = (TextView) findViewById(R.id.Direction);
		

		sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);		
		mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
	
	}

	@Override
	protected void onResume() {		
		super.onResume();		
		mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
	}



	private SensorManager mSensorManager;

	 public void onAccuracyChanged(Sensor sensor, int accuracy) {		 
		 //main.setText();		 
     }

     public void onSensorChanged(SensorEvent event) {
    	 
    	 
    	 
    	 float x = event.values[0];
    	 float y = event.values[1];
    	 float z = event.values[2];
    	 
    	 if (!mInitialized) {
    		 mInitialized = true;
    		 time = event.timestamp;
    		 mLastX = x;
    		 mLastY = y;
    		 mLastZ = z;
    		 
    		 X.setText("0.0");
    		 Y.setText("0.0");
    		 Z.setText("0.0");    		
    		
    	 }else {
    		 
    		 //if (((time -event.timestamp)*1000000000) < 1000000000){
    		 //	 return;
    			 
    		 //}
    		 ///float dif= event.timestamp-time;
    		 //main.setText(Float.toString(dif));
    		 //time=event.timestamp-time;
    		
    		 float deltaX = Math.abs(mLastX - x);
    		 float deltaY = Math.abs(mLastY - y);
    		 float deltaZ = Math.abs(mLastZ - z);

    		 if (deltaX < 2.0) deltaX = (float)0.0;
    		 if (deltaY < 2.0) deltaY = (float)0.0;
    		 if (deltaZ < 2.0) deltaZ = (float)0.0;

    		 mLastX = x;
    		 mLastY = y;
    		 mLastZ = z;

    		 X.setText(Float.toString(deltaX));
    		 Y.setText(Float.toString(deltaY));
    		 Z.setText(Float.toString(deltaZ));
    		 
    		 if (deltaX > deltaY) {
    			 Hcounter++;
    			
			 } else if (deltaY > deltaX) {
				 Vcounter++;
				
			 } 
			 
    		 Direction.setText("Vertical :" + Vcounter + " Horizontal: " + Hcounter);
			 
    		 
    		 
    	}
     }
}
